package com.example.micro_property_springboot.controller;

import com.example.micro_property_springboot.entity.SysNotificationSetting;
import com.example.micro_property_springboot.pojo.vo.NotificationSettingVO;
import com.example.micro_property_springboot.service.SysNotificationSettingService;
import com.example.micro_property_springboot.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 系统通知设置控制器
 * 提供通知设置相关的REST API接口
 */
@RestController
@RequestMapping("/api/system/notification")
public class SysNotificationSettingController {
    
    @Autowired
    private SysNotificationSettingService notificationSettingService;
    
    /**
     * 获取当前用户的通知设置
     */
    @GetMapping("/settings")
    public ResponseEntity<List<SysNotificationSetting>> getCurrentUserSettings() {
        Long userId = SecurityUtils.getCurrentUserId();
        List<SysNotificationSetting> settings = notificationSettingService.getByUserId(userId);
        
        // 如果没有设置，初始化默认设置
        if (settings == null || settings.isEmpty()) {
            notificationSettingService.initDefaultSettings(userId);
            settings = notificationSettingService.getByUserId(userId);
        }
        
        return ResponseEntity.ok(settings);
    }
    
    /**
     * 保存单个通知设置
     */
    @PutMapping("/setting")
    public ResponseEntity<Boolean> saveSetting(@RequestBody NotificationSettingVO settingVO) {
        // 确保设置属于当前用户
        Long userId = SecurityUtils.getCurrentUserId();
        settingVO.setUserId(userId);
        
        boolean result = notificationSettingService.saveOrUpdateSetting(settingVO);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 批量保存通知设置
     */
    @PutMapping("/settings")
    public ResponseEntity<Boolean> batchSaveSettings(@RequestBody List<NotificationSettingVO> settingVOs) {
        // 确保所有设置都属于当前用户
        Long userId = SecurityUtils.getCurrentUserId();
        settingVOs.forEach(vo -> vo.setUserId(userId));
        
        boolean result = notificationSettingService.batchSaveSettings(settingVOs);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 初始化默认通知设置
     */
    @PostMapping("/init-defaults")
    public ResponseEntity<Boolean> initDefaultSettings() {
        Long userId = SecurityUtils.getCurrentUserId();
        notificationSettingService.initDefaultSettings(userId);
        return ResponseEntity.ok(true);
    }
}